-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy path86. Partition List.py
115 lines (98 loc) · 2.52 KB
/
86. Partition List.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# Github: Shantanugupta1118
# DAY 50 of DAY 100
# 86. Partition List - Leetcode/LinkedList
# https://leetcode.com/problems/partition-list/
'''
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkediList:
def __init__(self):
self.head = None
def push(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
curr = self.head
while curr.next:
curr = curr.next
curr.next = new_node
def disp(self):
if self.head is None:
return None
curr = self.head
while curr:
print(curr.data, end= ' ')
curr = curr.next
print()
def partition(self, x):
def merge(small, high):
res = LinkediList()
curr = small.head
while curr:
res.push(curr.data)
curr = curr.next
curr = high.head
while curr:
res.push(curr.data)
curr = curr.next
return res
curr = self.head
small = LinkediList()
high = LinkediList()
while curr:
if curr.data < x:
small.push(curr.data)
else:
high.push(curr.data)
curr = curr.next
return merge(small, high)
'''
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
curr = self.head
while curr.next:
curr = curr.next
curr.next = new_node
def disp(self):
if self.head is None:
return None
curr = self.head
while curr:
print(curr.data, end= ' ')
curr = curr.next
print()
def partition(self, x):
curr = self.head
small_list = s = Node(0)
large_list = l = Node(0)
while curr:
if curr.data < x:
s.next = curr
s = s.next
else:
l.next = curr
l = l.next
curr = curr.next
l.next = None
s.next = large_list.next
return small_list.next
ll = LinkedList()
arr = [1, 4, 3, 2, 5, 2]
for i in arr:
ll.push(i)
ll.disp()
a = ll.partition(3)
a.disp()